package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.ResponseUtil;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin("*")
@RestController
@RequestMapping("/storage")
public class StorageController {
    @Autowired
    private StorageService storageService;
    //查询对象存储列表
    @GetMapping("/list")
    public Object list(String key, String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @RequestParam(defaultValue = "add_time") String sort,
                       @RequestParam(defaultValue = "desc") String order){
        //1. 查询并返回分页对象
        IPage<DtsStorage> resultPage = storageService.queryStoragePage(key,name,page,limit,sort,order);

        //获取结果集
        List<DtsStorage> list = resultPage.getRecords();
        //获取查询总条数
        long total = resultPage.getTotal();
        //封装对象返回
        Map<String,Object> data = new HashMap<>();
        data.put("total",total);
        data.put("items",list);
        return ResponseUtil.ok(data);
    }
        //文件上传
    @PostMapping("/create")
    public Object add(@RequestParam("file")MultipartFile file) throws Exception{

        //1. 获取文件名
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)){
            throw new RuntimeException("上传的文件为空d的话, 不允许上传!");

        }
        //2. 获取文件扩展名
        String ext = filename.substring(filename.lastIndexOf("."));

        //3. 获取文件大小
        long size = file.getSize();
        //4. 获取文件内容
        byte[] content = file.getBytes();

        //5. 上传并返回上传保存后的文件对象
        DtsStorage storage = storageService.add(filename, (int) size, ext, content);


        //6. 封装数据返回
        return ResponseUtil.ok(storage);
    }


    @PostMapping("/update")
    public Object update(@RequestBody  DtsStorage storage){

        int count = storageService.update(storage);
        if (count == 0){
            return ResponseUtil.fail();

        }
        return ResponseUtil.ok();
    }
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsStorage storage){
        //1. 提取文件对象中的key, 也就是阿里云中保存的文件名
        String key = storage.getKey();

        //2. 如果key为空, 那么不允许删除
        if (StringUtils.isEmpty(key)){
            return ResponseUtil.badArgument();

        }
        //3. 根据key调用service删除
        storageService.deleteByKey(key);
        //4. 返回
        return ResponseUtil.ok();
    }



}
